/*******************************************************************************
 * Copyright (c) 2008, 2009 Fabio Mauro - Alberto Terraneo.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 1.2
 * or any later version published by the Free Software Foundation.
 *     
 * This program is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied 
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 * See the GNU Free Documentation License for more details.
 *     
 * You should have received a copy of the GNU Free Documentation 
 * License along with this distribution; if not, send a email to authors:
 * aterraneo <at> users.sourceforge.net
 * bigmoby09 <at> users.sourceforge.net
 *******************************************************************************/
package it.blueocean.acanto.web.pages.secure.famiglia;

import it.blueocean.acanto.model.Famiglia;
import it.blueocean.acanto.model.Gruppo;
import it.blueocean.acanto.model.UserRole;
import it.blueocean.acanto.model.constants.StatoFamiglia;
import it.blueocean.acanto.service.FamigliaService;
import it.blueocean.acanto.service.GruppoService;
import it.blueocean.acanto.web.platform.components.dragdrop.ListViewPanel;
import it.blueocean.acanto.web.platform.components.feedback.ValidationStyleBehavior;
import it.blueocean.acanto.web.platform.components.panel.AcantoPanel;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxFallbackButton;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.ChoiceRenderer;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.IFormVisitorParticipant;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.value.ValueMap;
import org.odlabs.wiquery.ui.datepicker.InlineDatePicker;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;

public class NuovaFamiglia extends AcantoPanel
{
	private static final long serialVersionUID = 2022239405641534350L;

	@SpringBean
	private FamigliaService famigliaService;
	
	@SpringBean
	private GruppoService gruppoService;

	@SpringBean
	private PasswordEncoder passwordEncoder;

	@SpringBean
	private SaltSource saltSource;
	
	private Label name;

	public NuovaFamiglia(String id)
	{
		super(id);

		name = new Label("name", "crea nuovo utente");
		name.setOutputMarkupId(true);
		add(name);

		add(getComposedForm());
	}

	private AcantoStandardForm getComposedForm()
	{
		AcantoStandardForm form = new AcantoStandardForm("acantoStandardForm");
		form.setOutputMarkupId(true);

		form.add(new ListViewPanel<String>("listaGruppiDisponibili", getListaGruppi(), "stationary","listaGruppiDisponibili"));
		form.add(new ListViewPanel<String>("listaGruppiAppartenenza", getListaGruppi(), "stationary","listaGruppiAppartenenza"));

		TextField<String> cdg = new TextField<String>("cdg");
		cdg.setType(String.class);
		cdg.setRequired(true);
		cdg.setOutputMarkupId(true);
		cdg.add(new ValidationStyleBehavior());
		form.add(cdg);

		TextField<String> password = new TextField<String>("password");
		password.setType(String.class);
		password.setRequired(true);
		password.setOutputMarkupId(true);
		password.add(new ValidationStyleBehavior());
		form.add(password);

		TextField<String> cognomeReferente = new TextField<String>("cognomeReferente");
		cognomeReferente.setType(String.class);
		cognomeReferente.setRequired(true);
		cognomeReferente.setOutputMarkupId(true);
		cognomeReferente.add(new ValidationStyleBehavior());
		form.add(cognomeReferente);

		TextField<String> nomeReferente = new TextField<String>("nomeReferente");
		nomeReferente.setType(String.class);
		nomeReferente.setRequired(true);
		nomeReferente.setOutputMarkupId(true);
		nomeReferente.add(new ValidationStyleBehavior());
		form.add(nomeReferente);

		TextField<String> note = new TextField<String>("note");
		note.setType(String.class);
		note.setOutputMarkupId(true);
		form.add(note);

		InlineDatePicker<Date> assenteDal = new InlineDatePicker<Date>("assenteDal");
		form.add(assenteDal);

		InlineDatePicker<Date> assenteAl = new InlineDatePicker<Date>("assenteAl");
		form.add(assenteAl);

		DropDownChoice<String> status = new DropDownChoice<String>("status",
				new LoadableDetachableModel<List<String>>()
				{
					private static final long serialVersionUID = 1L;

					@Override
					protected List<String> load()
					{
						return StatoFamiglia.getListStringStatiFamigliaEnumValues();
					}
				});
		status.setRequired(true);
		status.setOutputMarkupId(true);
		status.add(new ValidationStyleBehavior());
		form.add(status);

		CheckBox checkEnabledFamiglia = new CheckBox("checkEnabledFamiglia", new PropertyModel<Boolean>(new Model<Boolean>(Boolean.FALSE), "value"));
		checkEnabledFamiglia.setOutputMarkupId(true);
		checkEnabledFamiglia.setRequired(true);
		checkEnabledFamiglia.add(new ValidationStyleBehavior());
		form.add(checkEnabledFamiglia);

		DropDownChoice<UserRole> authorizationRole = new DropDownChoice<UserRole>("authorizationRole",
				new LoadableDetachableModel<List<UserRole>>()
				{
					private static final long serialVersionUID = -8189203261004116433L;

					@Override
					protected List<UserRole> load()
					{
						return UserRole.getListUserRole();
					}

				}, new ChoiceRenderer<UserRole>("valore"));
		authorizationRole.setRequired(true);
		authorizationRole.setOutputMarkupId(true);
		authorizationRole.add(new ValidationStyleBehavior());
		form.add(authorizationRole);

		form.add(new AjaxFallbackButton("submitButton", form)
		{
			private static final long serialVersionUID = 159710398094370478L;

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form)
			{
				ValueMap values = (ValueMap) form.getDefaultModelObject();

				String cdg = values.getString("cdg");
				String password = values.getString("password");
				String cognomeReferente = values.getString("cognomeReferente");
				String nomeReferente = values.getString("nomeReferente");
				String note = values.getString("note");
				// Time assenteDal = values.getTime("assenteDal");
				// Time assenteAl = values.getTime("assenteAl");
				String status = values.getString("status");

				Boolean enabled = values.getBoolean("checkEnabledFamiglia");
				String authorizationRole = values.getString("authorizationRole");

				Famiglia famiglia = new Famiglia();
				famiglia.setCdg(cdg);
				famiglia.setPassword(password);
				famiglia.setCognomeReferente(cognomeReferente);
				famiglia.setNomeReferente(nomeReferente);
				famiglia.setNote(note);
				// famiglia.setAssenteDal(assenteDal);
				// famiglia.setAssenteAl(assenteAl);
				famiglia.setStatus(StatoFamiglia.getFromValue(status));
				famiglia.setEnabled(enabled);
				famiglia.setAuthorizationRole(authorizationRole);

				famigliaService.store(famiglia);

				famiglia = famigliaService.extractByCdg(cdg);

				Object salt = saltSource.getSalt(famiglia);
				famiglia.setPassword(passwordEncoder.encodePassword(password, salt));
				famigliaService.store(famiglia);

				getSuccessFeedbackModalWindow().show(target);
			}

			@Override
			protected void onError(final AjaxRequestTarget target, Form<?> form)
			{
				form.visitFormComponents(new IVisitor()
				{
					public Object formComponent(IFormVisitorParticipant formVisitor)
					{
						if(formVisitor instanceof FormComponent)
						{
							FormComponent<?> formComponent = (FormComponent<?>) formVisitor;
							target.addComponent(formComponent);
						}
						return formVisitor;
					}
				});

				getErrorFeedbackModalWindow().show(target);
			}
		});

		return form;
	}

	private List<String> getListaGruppi()
	{
		final List<String> listaGruppiDisponibili = new ArrayList<String>();
		List<Gruppo> listGruppi = gruppoService.extractAll();
		for (Iterator<Gruppo> iterator = listGruppi.iterator(); iterator.hasNext();)
		{
			Gruppo gruppo = iterator.next();
			listaGruppiDisponibili.add(gruppo.getId());
		}

		return listaGruppiDisponibili;
	}

}
